package ch.sv7.tool.dbmanager.types;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Get the TypesInfo from the given Connection directly 
 * from JDBC metadata
 *
 * @author svt
 *
 */
public class ConnectionTypesInfo implements TypesInfo {

	protected Map typesMap = new HashMap();
	
	public ConnectionTypesInfo(Connection conn) throws SQLException {
		super();
		readFromConnection(conn);
	}

	protected void readFromConnection(Connection conn) throws SQLException {
		ResultSet rs = null;
		try {
			DatabaseMetaData metaData = conn.getMetaData();
			rs = metaData.getTypeInfo();
		
			while (rs.next()){
				TypeInfo type = new TypeInfo(
						rs.getString("TYPE_NAME"),
						rs.getInt("DATA_TYPE"),
						rs.getInt("PRECISION"),
						rs.getString("LITERAL_PREFIX"),
						rs.getString("LITERAL_SUFFIX"),
						rs.getString("CREATE_PARAMS"),
						rs.getShort("NULLABLE"),
						rs.getBoolean("CASE_SENSITIVE"),
						rs.getShort("SEARCHABLE"),
						rs.getBoolean("UNSIGNED_ATTRIBUTE"),
						rs.getBoolean("FIXED_PREC_SCALE"),
						rs.getBoolean("AUTO_INCREMENT"),
						rs.getString("LOCAL_TYPE_NAME"),
						rs.getShort("MINIMUM_SCALE"),
						rs.getShort("MAXIMUM_SCALE"),
						rs.getInt("NUM_PREC_RADIX")
				);
				//int sqlDataType = rs.getInt("SQL_DATA_TYPE"); //unused
				//int sqlDateTime = rs.getInt("SQL_DATETIME_SUB"); // unused
				
				typesMap.put(type.getTypeName(), type);
			}

		} finally {
			if (rs != null){
				rs.close();
			}
		}
	}
	
	public TypeInfo getTypeInfo(String typeName) {
		return (TypeInfo)typesMap.get(typeName);
	}

	public String[] getTypeNames() {
		String[] result = new String[typesMap.size()];
		Iterator iter = typesMap.keySet().iterator();
		int i = 0;
		while (iter.hasNext()){
			String type = (String)iter.next();
			result[i++] = type;
		}
		
		return result;
	}

}
